package config

import (
	"fmt"
	"cli"
	"gopkg.in/yaml.v2"
	"os"
)

var Config *config

type config struct{
	Web *Web `yaml:"web"`
	Mysql *Mysql `yaml:"mysql"`
}

type Web struct {
	Port string `yaml:"port"`
}

type Mysql struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
}

// 返回具体的连接
// username:password@protocol(address)/dbname?param=value
func (m Mysql) DSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		m.Username,
		m.Password,
		m.Host,
		m.Port,
		m.Database,
	)
}
func Init(ctx *cli.Context) error {
	err := initConfig(ctx)
	if err != nil {
		return err
	}
	return nil
}

func initConfig(ctx *cli.Context) error {
	conf := ctx.String("c")
	f,err := os.Open(conf)
	if err != nil {
		return err
	}
	Config = new(config)
	err = yaml.NewDecoder(f).Decode(Config)
	if err != nil {
		return err
	}
	return nil
}
